<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: Circle.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\data\note;

use app\api\model\dao\Note;
use app\api\model\dao\Circle;
use app\api\model\dao\NotePraise;
use app\api\model\dao\NoteReply;
use app\api\model\dao\NoteStatistics;
use app\api\model\dao\UserAccount;
use app\api\model\dao\UserCurrency;
use app\library\Common;
use app\library\CommonConfig;
use app\library\Flag;

use think\Log;

class NoteData
{

    private $objNote;
    private $objCircle;
    private $objUserAccount;
    private $objNotePraise;
    private $objNoteReply;
    private $objNoteStatistics;
    private $objUserCurrency;

    public function __construct()
    {
        $this->objNote = new Note();
        $this->objCircle = new Circle();
        $this->objUserAccount = new UserAccount();
        $this->objNotePraise = new NotePraise();
        $this->objNoteReply = new NoteReply();
        $this->objNoteStatistics = new NoteStatistics();
        $this->objUserCurrency = new UserCurrency();
    }

    /**
     * 精选帖子
     *
     * @param int $cir_id
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public function exquisiteNote($cir_id = 0, $offset = 0, $limit = 10)
    {
        if ($cir_id) {
            $sql = sprintf("select * from note where cir_id=%d and is_delete=%d and flag & %d = %d order by create_time desc limit %d,%d", $cir_id, Flag::CONST_NOTE_DELETE_NOT, Flag::FLAG_NOTE_EXQUISITE, Flag::FLAG_NOTE_EXQUISITE, $offset, $limit);
            $cntsql = sprintf("select count(*) as cnt from note where cir_id=%d and flag & %d = %d", $cir_id, Flag::CONST_NOTE_DELETE_NOT, Flag::FLAG_NOTE_EXQUISITE, Flag::FLAG_NOTE_EXQUISITE);
        } else {
            $sql = sprintf("select * from note where is_delete=%d and flag & %d = %d order by create_time desc limit %d,%d", Flag::CONST_NOTE_DELETE_NOT, Flag::FLAG_NOTE_EXQUISITE, Flag::FLAG_NOTE_EXQUISITE, $offset, $limit);
            $cntsql = sprintf("select count(*) as cnt from note where is_delete=%d and flag & %d = %d", Flag::CONST_NOTE_DELETE_NOT, Flag::FLAG_NOTE_EXQUISITE, Flag::FLAG_NOTE_EXQUISITE);
        }
        $retNote = $this->objNote->db()->query($sql);
        empty($retNote) && $retNote = [];

        $total = 0;

        $cnt_ret = $this->objNote->db()->query($cntsql);
        if (!empty($cnt_ret)) {
            $total = $cnt_ret[0]['cnt'];
        }

        $more = $limit - count($retNote);

        if ($more > 0) {

            if ($more < $limit) {
                $offset = 0;
                $limit = $more;
            } else {
                $offset = $offset - $total + 1;
            }

            $arrCond = [
                'is_delete' => ['=', Flag::CONST_NOTE_DELETE_NOT]
            ];
            if ($cir_id) {
                $arrCond['cir_id'] = ['=', $cir_id];
            }
            $note_ret = $this->objNote->getNote($arrCond, [], $offset, $limit, ' create_time desc ');
            if (false === $note_ret) {
                Log::error(__METHOD__ . ' get note list fail.');
                $note_ret = [];
            }
            $retNote = array_merge($retNote, $note_ret);
        }

        return $this->composeNote($retNote);
    }

    /**
     * 最热帖子
     * 进入详情页PV量排序
     *
     * @param int $cir_id
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public function hotNote($cir_id = 0, $offset = 0, $limit = 10)
    {
        $note_ids = [];

        if ($cir_id) {
            $sql = sprintf("select * from note where cir_id=%d and is_delete=%d and flag & %d = %d order by create_time desc limit %d,%d", $cir_id, Flag::CONST_NOTE_DELETE_NOT, Flag::FLAG_NOTE_HOT, Flag::FLAG_NOTE_HOT, $offset, $limit);
            $cntsql = sprintf("select count(*) as cnt from note where cir_id=%d and is_delete=%d and flag & %d = %d", $cir_id, Flag::CONST_NOTE_DELETE_NOT, Flag::FLAG_NOTE_HOT, Flag::FLAG_NOTE_HOT);
        } else {
            $sql = sprintf("select * from note where is_delete=%d and flag & %d = %d order by create_time desc limit %d,%d", Flag::CONST_NOTE_DELETE_NOT, Flag::FLAG_NOTE_HOT, Flag::FLAG_NOTE_HOT, $offset, $limit);
            $cntsql = sprintf("select count(*) as cnt from note where is_delete=%d and flag & %d = %d", Flag::CONST_NOTE_DELETE_NOT, Flag::FLAG_NOTE_HOT, Flag::FLAG_NOTE_HOT);
        }
        $retNote = $this->objNote->db()->query($sql);
        empty($retNote) && $retNote = [];
        foreach ($retNote as $note) {
            $note_ids[] = $note['id'];
        }

        $total = 0;

        $cnt_ret = $this->objNote->db()->query($cntsql);
        if (!empty($cnt_ret)) {
            $total = $cnt_ret[0]['cnt'];
        }

        $more = $limit - count($retNote);

        if ($more > 0) {

            if ($more < $limit) {
                $offset = 0;
                $limit = $more;
            } else {
                $offset = $offset - $total + 1;
            }

            $arrCond = [];
            if ($cir_id) {
                $arrCond['cir_id'] = ['=', $cir_id];
            }
            $noteStatistics_ret = $this->objNoteStatistics->getNoteStatistics($arrCond, [], $offset, $limit, ' pv desc ');
            empty($noteStatistics_ret) && $noteStatistics_ret = [];
            foreach ($noteStatistics_ret as $note_statistics) {
                $note_ids[] = $note_statistics['note_id'];
            }
        }

        if (empty($note_ids)) {
            return [];
        }

        $arrCond = [
            'id' => ['in', array_unique($note_ids)],
            'is_delete' => ['=', Flag::CONST_NOTE_DELETE_NOT]
        ];
        $retNote = $this->objNote->getNote($arrCond);
        if (false === $retNote) {
            Log::error(__METHOD__ . ' get note list fail.');
            return [];
        }

        return $this->composeNote($retNote);
    }

    /**
     * 最新帖子
     *
     * @param int $cir_id
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public function newNote($cir_id = 0, $offset = 0, $limit = 10)
    {
        $arrCond = [
            'is_delete' => ['=', Flag::CONST_NOTE_DELETE_NOT]
        ];
        if ($cir_id) {
            $arrCond['cir_id'] = ['=', $cir_id];
        }
        $retNote = $this->objNote->getNote($arrCond, [], $offset, $limit, ' create_time desc ');
        if (false === $retNote) {
            Log::error(__METHOD__ . ' get note list fail.');
            return [];
        }

        return $this->composeNote($retNote);
    }

    /**
     * 原创帖子
     *
     * @param int $cir_id
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public function originalNote($cir_id = 0, $offset = 0, $limit = 10)
    {
        $arrCond = [
            'original' => ['=', Flag::CONST_NOTE_ORIGINAL],
            'is_delete' => ['=', Flag::CONST_NOTE_DELETE_NOT]
        ];
        if ($cir_id) {
            $arrCond['cir_id'] = ['=', $cir_id];
        }
        $retNote = $this->objNote->getNote($arrCond, [], $offset, $limit, ' create_time desc ');
        if (false === $retNote) {
            Log::error(__METHOD__ . ' get note list fail.');
            return [];
        }

        return $this->composeNote($retNote);
    }

    /**
     * 我发出的帖子
     *
     * @param int $userid
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public function mineNote($userid, $offset = 0, $limit = 10)
    {
        $arrCond = [
            'is_delete' => ['=', Flag::CONST_NOTE_DELETE_NOT]
        ];
        $arrCond['creator'] = ['=', $userid];
        $retNote = $this->objNote->getNote($arrCond, [], $offset, $limit, ' create_time desc ');
        if (false === $retNote) {
            Log::error(__METHOD__ . ' get note list fail.');
            return [];
        }

        return $this->composeNote($retNote);
    }

    /**
     * 待审核帖子
     *
     * @param int $cir_id
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public function approveNote($arrCirid, $offset = 0, $limit = 10)
    {
        $arrCond = [
            'cir_id' => ['in', $arrCirid],
            'approve_status' => ['=', Flag::CONST_NOTE_APPROVE],
            'is_delete' => ['=', Flag::CONST_NOTE_DELETE_NOT]
        ];
        $retNote = $this->objNote->getNote($arrCond, [], $offset, $limit, ' create_time desc ');
        if (false === $retNote) {
            Log::error(__METHOD__ . ' get note list fail.');
            return [];
        }

        return $this->composeNote($retNote);
    }

    /**
     * 我发出的帖子数量
     *
     * @param int $userid
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public function mineNoteCount($userid, $date = 0)
    {
        $arrCond = [
            'is_delete' => ['=', Flag::CONST_NOTE_DELETE_NOT]
        ];
        $arrCond['creator'] = ['=', $userid];
        if ($date) {
            $arrCond['date'] = ['=', $date];
        }
        $retNoteCount = $this->objNote->getNoteCount($arrCond);
        if (false === $retNoteCount) {
            Log::error(__METHOD__ . ' get note list fail.');
            return 0;
        }

        return $retNoteCount;
    }

    /**
     * 我评论过的帖子
     *
     * @param int $cir_id
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public function replyNote($userid, $offset = 0, $limit = 10)
    {
        $arrCond = [
            'userid' => ['=', $userid],
            'is_delete' => ['=', Flag::CONST_NOTEREPLY_DELETE_NOT]
        ];
        $note_replay = $this->objNoteReply->getNoteReply($arrCond, ['note_id']);
        if (empty($note_replay)) {
            Log::error(__METHOD__ . ' get note reply fail.');
            return [];
        }
        $noteid = [];
        foreach ($note_replay as $val) {
            $noteid[] = $val['note_id'];
        }
        $arrCond = [
            'id' => ['in', $noteid],
            'is_delete' => ['=', Flag::CONST_NOTE_DELETE_NOT]
        ];
        $retNote = $this->objNote->getNote($arrCond, [], $offset, $limit, ' create_time desc ');
        if (false === $retNote) {
            Log::error(__METHOD__ . ' get note list fail.');
            return [];
        }

        return $this->composeNote($retNote);
    }

    /**
     * 组装帖子所有数据
     *
     * @param $arrNote
     * @return array
     */
    public function composeNote($arrNote)
    {
        if (empty($arrNote)) {
            return [];
        }

        $userid = [];
        $noteid = [];
        $cirid = [];
        $user_account = [];
        $user_integral = [];

        foreach ($arrNote as $note) {
            $userid[] = $note['creator'];
            $noteid[] = $note['id'];
            $cirid[] = $note['cir_id'];
        }

        // 获取圈子信息
        $circle = [];
        if ($cirid) {
            $arrCond = [
                'id' => ['in', $cirid]
            ];
            $cirRet = $this->objCircle->getCircle($arrCond, ['id', 'name', 'icon']);
            if (!empty($cirRet)) {
                foreach ($cirRet as $cir) {
                    $circle[$cir['id']]['name'] = $cir['name'];
                    $circle[$cir['id']]['icon'] = $cir['icon'];
                }
            }
        }

        // 获取用户信息
        if (!empty($userid)) {
            $user_account_ret = $this->objUserAccount->getUserAccountByUserids($userid, ['id', 'nick_name', 'sex', 'level', 'avatar']);
            if (!empty($user_account_ret)) {
                $user_account_ret = Common::modelToArray($user_account_ret);
            } else {
                $user_account_ret = [];
            }
            foreach ($user_account_ret as $user) {
                $user_account[$user['id']] = $user;
            }
            $user_integral_ret = $this->objUserCurrency->getCurrencyByUserids($userid, Flag::CURENCY_TYPE_INTEGRAL);
            if (!empty($user_integral_ret)) {
                $user_integral_ret = Common::modelToArray($user_integral_ret);
            } else {
                $user_integral_ret = [];
            }
            foreach ($user_integral_ret as $integral) {
                $user_integral[$integral['user_id']] = $integral['amount'];
            }
        }

        // 获取赞信息
        $note_priase_count = [];
        if (!empty($noteid)) {
            $praise_ret = $this->objNotePraise->getNotePraiseCount($noteid);
            if (!empty($praise_ret)) {
                foreach ($praise_ret as $praise) {
                    $note_priase_count[$praise['note_id']] = $praise['cnt'];
                }
            }
        }
        $note_priase_count = $note_priase_count ? $note_priase_count : [];

        // 获取回复信息
        $note_reply_count = [];
        if (!empty($noteid)) {
            $replay_ret = $this->objNoteReply->getNoteReplyCount($noteid);
            if (!empty($replay_ret)) {
                foreach ($replay_ret as $reply) {
                    $note_reply_count[$reply['note_id']] = $reply['cnt'];
                }
            }
        }
        $note_reply_count = $note_reply_count ? $note_reply_count : [];

        $i = 0;
        $data = [];
        foreach ($arrNote as $note) {
            $note_reply_num = isset($note_reply_count[$note['id']]) && !empty($note_reply_count[$note['id']]) ? $note_reply_count[$note['id']] : 0;
            $note_praise = isset($note_priase_count[$note['id']]) && !empty($note_priase_count[$note['id']]) ? $note_priase_count[$note['id']] : 0;
            if (isset($user_account[$note['creator']]) && !empty($user_account[$note['creator']])) {
                $name = $user_account[$note['creator']]['nick_name'] ? $user_account[$note['creator']]['nick_name'] : '踏着尸体前行';
                $sex = $user_account[$note['creator']]['sex'] ? 'F' : 'M';
                $level = $user_account[$note['creator']]['level'];
                $photo = $user_account[$note['creator']]['avatar'] ? $user_account[$note['creator']]['avatar'] : CommonConfig::DEFAULT_AVATAR;
                $userid = $user_account[$note['creator']]['id'];
            } else {
                continue;
            }

            $integral = !empty($user_integral[$note['creator']]) ? $user_integral[$note['creator']] : 0;
            $level = Common::conversionLevel($integral);

            $data[$i] = [
                'note_id' => $note['id'],
                'userid' => $userid,
                'name' => $name,
                'photo' => $photo,
                'sex' => $sex,
                'level' => $level,
                'title' => $note['title'],
                'content' => $note['content'],
                'cir_name' => isset($circle[$note['cir_id']]) && !empty($circle[$note['cir_id']]['name']) ? $circle[$note['cir_id']]['name'] : '',
                'cir_icon' => isset($circle[$note['cir_id']]) && !empty($circle[$note['cir_id']]['icon']) ? $circle[$note['cir_id']]['icon'] : '',
                'note_reply_num' => $note_reply_num,
                'note_praise' => $note_praise,
                'time' => $this->caleDate($note['create_time']),
            ];
            if ($note['pic']) {
                $data[$i]['pic'] = explode(',', urldecode($note['pic']));
            } else {
                $data[$i]['pic'] = [];
            }
            $i++;
        }
        return $data;
    }

    public function caleDate($timestamp)
    {
        $now = time();
        $subtraction = $now - $timestamp;
        if ($subtraction < 60) {
            return $subtraction . '秒前';
        } else if ($subtraction < 3600) {
            return floor($subtraction / 60) . '分钟前';
        } else if ($subtraction < 86400) {
            return floor($subtraction / 3600) . '小时前';
        } else if ($subtraction < 2592000) {
            return floor($subtraction / 86400) . '天前';
        } else {
            return floor($subtraction / 2592000) . '月前';
        }
    }
}
